/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ipinyou.wordstatistics.core;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author xiangnan.wang@ipinyou.com
 */
public class ResourceSearch {

    //文件过滤器
    private FileFilter filter;
    
    //要搜索的路径
    private String path;
    
    private volatile IHandleDoneListener listener;
    
    private List<HandleResult> results;
    
    
    public void setHandleDoneListener(IHandleDoneListener listener){
        this.listener=listener;
    }
    
    public ResourceSearch(FileFilter filter,String path){
        assert path.length()>0;
        String last=path.substring(path.length()-1);
        this.path=path;
        this.filter=filter;
        results=new ArrayList<HandleResult>();
    }
    
    public void search(ISearchResultHandler handler){
        File dir=new File(path);
        search0(dir,handler);
        if(listener!=null){
            listener.handle(results);
        }
    }
    
    private void search0(File dir,ISearchResultHandler handler) {
        if (dir.isDirectory()) {
            File[] files = dir.listFiles(filter);
            for (File f : files) {
                if (f.isDirectory()) {
                    search0(f,handler);
                } else {
                    HandleResult result=handler.handler(f);
                    if(result.isContainCodes()){
                        results.add(handler.handler(f));
                    }
                }
            }
        }
    }
}
